import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import { Table, Row, Col, Button, Drawer, Form, Input, Select, DatePicker, Radio, message ,Icon,Upload} from 'antd';
import { addRegist, getUserTable } from '@/config/api'
import { Httpost, Httpget } from '@/config/request'
const { Option } = Select;

const columns = [
    {
        title: '姓名',
        dataIndex: 'username',
        width: 100,
        key: 'username',
    },
    {
        title: '密码',
        dataIndex: 'password',
        width: 100,
        key: 'password',
    },
    {
        title: '性别',
        dataIndex: 'gender',
        width: 70,
        key: 'gender',
    }, {
        title: '出生日期',
        dataIndex: 'birth',
        width: 120,
        key: '4',
    },
    {
        title: '是否管理员',
        dataIndex: 'isAdmin',
        width: 150,
        key: 'isAdmin',
    },
    {
        title: '电话',
        dataIndex: 'phone',
        width: 150,
        key: 'phone',
    },

    {
        title: '地址',
        dataIndex: 'location',
        key: 'location',
        width: 150,
    },



];


function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }
  
  function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

class User extends Component {
    constructor(porps) {
        super(porps)
        this.state = {
            visible: false,
            data: [],
            imageUrl:''
        };

    }
    componentDidMount() {
        this.initTable()
    }
    initTable() {
        Httpget(getUserTable).then((res) => {
            if (res.resultCode === 200) {
                this.setState({
                    data: res.data.reverse()
                })
            } else {
                message.error(res.msg)
            }
        }).catch((res) => {
            message.error(res.msg)
        })
    }

    onClose = () => {
        this.setState({
            visible: false,
        });
    };

    addUser = () => {
        this.setState({
            visible: true,
        });
    }
    addRegist = () => {
        let param = this.props.form.getFieldsValue()
        Httpost(addRegist, param).then((res) => {
            if (res.resultCode === 200) {
                message.success(res.msg)
                this.initTable()
                this.onClose()
                this.props.form.resetFields();
            } else {
                message.error(res.msg)
            }
        }).catch((res) => {
            message.error(res.msg)
        })
    }
    handleChange = info => {
        if (info.file.status === 'uploading') {
          this.setState({ loading: true });
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          getBase64(info.file.originFileObj, imageUrl =>
            this.setState({
              imageUrl,
              loading: false,

            }),
          );
        }
      };

    render() {
        const { getFieldDecorator } = this.props.form;
        const uploadButton = (
            <div>
              <Icon type={this.state.loading ? 'loading' : 'plus'} />
              <div className="ant-upload-text">Upload</div>
            </div>
          );
          const { imageUrl } = this.state;
        return (
            <div>
                <Row type="flex" justify="end">

                    <Col span={1}>
                        <Button type="primary" icon="plus" size='small' onClick={this.addUser}>新增</Button>
                    </Col>
                </Row>
                <Table columns={columns} dataSource={this.state.data} scroll={{ x: 1500, y: 300 }} />
                <Drawer
                    title="Create a new account"
                    width={720}
                    onClose={this.onClose}
                    visible={this.state.visible}
                >
                    <Form layout="vertical" hideRequiredMark>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="姓名">
                                    {getFieldDecorator('username', {
                                        rules: [{ required: true, message: 'Please enter user username' }],
                                    })(<Input placeholder="Please enter user username" />)}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="密码">
                                    {getFieldDecorator('password', {
                                        rules: [{ required: true, message: 'Please enter password' }],
                                        initialValue: '123456'
                                    })(
                                        <Input
                                            style={{ width: '100%' }}
                                            placeholder="Please enter password"
                                        />,
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="地址">
                                    {getFieldDecorator('registrationAddress', {
                                        rules: [{ required: true, message: 'Please select an registrationAddress' }],
                                        initialValue: '1'
                                    })(
                                        <Select placeholder="Please select an registrationAddress">
                                            <Option value="1">北京</Option>
                                            <Option value="2">上海</Option>
                                            <Option value="3">天津</Option>
                                            <Option value="4">广州</Option>
                                            <Option value="5">深证</Option>
                                            <Option value="6">珠海</Option>
                                            <Option value="7">武汉</Option>
                                        </Select>,
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="注册时间">
                                    {getFieldDecorator('registrationTime', {
                                        rules: [{ required: true, message: 'Please choose the registrationTime' }],
                                    })(
                                        <DatePicker
                                            style={{ width: '100%' }}

                                        />,
                                    )}
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row gutter={16}>
                            <Col span={12}>
                                <Form.Item label="是否管理员">
                                    {getFieldDecorator('isAdmin', {
                                        rules: [{ required: true, message: 'Please choose the isAdmin' }],
                                        initialValue: '0'
                                    })(
                                        <Radio.Group name="radiogroup" >
                                            <Radio value='0'>否</Radio>
                                            <Radio value='1'>是</Radio>
                                        </Radio.Group>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="头像">
                                    {getFieldDecorator('avatar', {
                                        rules: [{ required: true, message: 'Please choose the avatar' }],
                                    })(
                                        <Upload
                                        name="avatar"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                        beforeUpload={beforeUpload}
                                        onChange={this.handleChange}
                                      >
                                        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                                      </Upload>,
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="出生日期">
                                    {getFieldDecorator('birth', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'please enter url birth',
                                            },
                                        ],
                                    })(<DatePicker placeholder="please enter url birth" />)}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="手机号码">
                                    {getFieldDecorator('phone', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'please enter url phone',
                                            },
                                        ],
                                    })(<Input placeholder="please enter url phone" />)}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="所在地">
                                    {getFieldDecorator('location', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'please enter url location',
                                            },
                                        ],
                                    })(<Input placeholder="please enter url location" />)}
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="性别">
                                    {getFieldDecorator('gender', {
                                        rules: [
                                            {
                                                required: true,
                                                message: 'please enter url gender',
                                            }
                                        ], initialValue: '1'
                                    })(<Radio.Group name="radiogroup" >
                                        <Radio value='1'>男</Radio>
                                        <Radio value='0'>女</Radio>
                                    </Radio.Group>)}
                                </Form.Item>
                            </Col>
                        </Row>

                    </Form>
                    <div
                        style={{
                            position: 'absolute',
                            left: 0,
                            bottom: 0,
                            width: '100%',
                            borderTop: '1px solid #e9e9e9',
                            padding: '10px 16px',
                            background: '#fff',
                            textAlign: 'right',
                        }}
                    >
                        <Button onClick={this.onClose} style={{ marginRight: 8 }}>
                            Cancel
            </Button>
                        <Button onClick={this.addRegist} type="primary">
                            Submit
            </Button>
                    </div>
                </Drawer>
            </div>
        )
    }
}
const App = Form.create()(User);

export default withRouter(App)